#include "tcp_connect.h"

TcpConnect::TcpConnect(int fd)
    : clifd_(fd)
{
}

TcpConnect::~TcpConnect()
{
    cout << "disconnect: " << getPeer() << endl;
    ::close(clifd_);
}

void TcpConnect::handleRequest()
{
    // 获取客户端请求
    struct Protocol proto{};
    int ret = ::recv(clifd_, &proto.behavior_, sizeof(short), 0);
    ERR_CHECK(ret, -1, "handleRequest recv")
    ret = ::recv(clifd_, proto.buf_, PROTOCOL_BUF_LEN - 1, 0);
    ERR_CHECK(ret, -1, "handleRequest recv")

    // 使用解析器，解析
    ParserPtr parser = Parser::getInst();
    parser->parse(proto);

#ifdef DEBUG
    cout << proto.buf_ << endl;
#endif
}

string TcpConnect::getPeer()
{
    struct sockaddr_in sock{};
    socklen_t len = sizeof(sock);
    int ret = getpeername(clifd_, (struct sockaddr *)&sock, &len);
    if (ret < 0)
    {
        perror("getpeername");
        exit(0);
    }

    return string(inet_ntoa(sock.sin_addr)) + " : " + std::to_string(ntohs(sock.sin_port));
}

bool TcpConnect::isClose()
{
    char buf[4]{};
    // MSG_PEEK 读完数据后不会清除缓冲区中的已读数据
    int ret = ::recv(clifd_, buf, 4, MSG_PEEK);
    return ret == 0;
}